package com.situ.mall.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.situ.mall.common.entity.Member;
import com.situ.mall.common.exception.NoLoginException;
import com.situ.mall.common.util.RequestUtil;
import com.situ.mall.common.entity.Cart;
import com.situ.mall.common.mapper.CartMapper;
import com.situ.mall.order.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.situ.mall.common.vo.CartVO;
import com.situ.mall.order.vo.LayuiTableVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author membergpf
 * @since 2023-03-18
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Autowired
    CartMapper cartMapper;

    @Override
    public LayuiTableVO selectAll(Integer page, Integer limit) {
        LayuiTableVO vo = new LayuiTableVO();

        //查询前，分页工具介入
        PageHelper.startPage(page,limit);//加入startPage方法后，后面的查询就开启分页查，自动加limit
        //startPage方法后第一次查询是分页，是一次性的
        vo.setData(cartMapper.selectAll());
        vo.setCode(0);

        return vo;
    }

    @Override
    public void addToCart(Integer ProductId) {
        Member m = RequestUtil.getCurrent();//原来是order
        if(m==null){//还没登录

            throw new NoLoginException();
        }

        Cart c= baseMapper.selectByMemberIdAndProdunctId(m.getId(),ProductId);
        //判断此产品之前是否加入过购物车
        if (c == null) {
            Cart cart = new Cart();
            cart.setAmount(1);
            cart.setProductId(ProductId);
            cart.setCreatetime(LocalDateTime.now());
            cart.setMemberId(m.getId());//当前会员id
            baseMapper.insert(cart);

        }else {//如果加入过
            baseMapper.updateAmount(c.getId());
        }

        //如果加入过，把对应的数据数量+1
    }

    @Override
    public List<CartVO> selectList() {
        //获取当前登录用户member
        Member m= RequestUtil.getCurrent();//order


        return baseMapper.selectCartList(m.getId());
    }

    @Override
    public void delete(Integer cartid) {
        baseMapper.deleteById(cartid);
    }

    @Override
    public void updateAmount(Integer cartid, Integer num) {
        baseMapper.updateAmount(cartid,num);
    }

    @Override
    public List<CartVO> list1(String ids) {
        List<CartVO>list =new ArrayList<>();
        Member m=RequestUtil.getCurrent();
        for(String cartId :ids.split(",")){
            CartVO vo= baseMapper.selectOrderList(Integer.parseInt(cartId),m.getId());
            list.add(vo);
        }
        return list;
    }
}
